import cv2
import os
import numpy as np



def combine_tiles_into_larger_tiles(input_dir, output_dir, small_tile_size=256, large_tile_size=512):
    # 创建输出目录
    os.makedirs(output_dir, exist_ok=True)

    # 获取所有小块图像文件
    tile_files = sorted([f for f in os.listdir(input_dir) if f.endswith('.png')])

    # 创建一个字典以存储小块图像
    tiles = {}

    for tile_file in tile_files:
        # 提取行和列编号
        parts = tile_file.split('_')
        row = int(parts[1])
        col = int(parts[2].split('.')[0])

        # 加载图像块
        tile_path = os.path.join(input_dir, tile_file)
        tile = cv2.imread(tile_path)
        tiles[(row, col)] = tile

    # 组合小块图像为大块图像
    rows = max(key[0] for key in tiles.keys()) + 1
    cols = max(key[1] for key in tiles.keys()) + 1

    for row in range(0, rows - 1):
        for col in range(0, cols - 1):
            if (row, col) in tiles and (row, col + 1) in tiles and (row + 1, col) in tiles and (
            row + 1, col + 1) in tiles:
                # 创建一个空白大块图像
                large_tile = np.zeros((large_tile_size, large_tile_size, 3), dtype=np.uint8)

                # 填充大块图像
                large_tile[0:small_tile_size, 0:small_tile_size] = tiles[(row, col)]
                large_tile[0:small_tile_size, small_tile_size:large_tile_size] = tiles[(row, col + 1)]
                large_tile[small_tile_size:large_tile_size, 0:small_tile_size] = tiles[(row + 1, col)]
                large_tile[small_tile_size:large_tile_size, small_tile_size:large_tile_size] = tiles[(row + 1, col + 1)]

                # 生成大块图像文件名
                large_tile_filename = f"tile_({row}_{col},{row + 1}_{col + 1}).png"

                # 保存大块图像
                cv2.imwrite(os.path.join(output_dir, large_tile_filename), large_tile)


# 示例用法
output_dir_small = r'E:\wafer52\11866_256nm_split'
output_dir_large = r'E:\wafer52\11867_256nm_combine'

combine_tiles_into_larger_tiles(output_dir_small, output_dir_large, small_tile_size=128, large_tile_size=256)

print(f"Small tiles saved to {output_dir_small}")
print(f"Large tiles saved to {output_dir_large}")
